
import ttable from '@/components/common/TTable.vue'
import varea from './comp/ImportArea.vue'
import vship from './comp/ImportShip'
import MapDraw from './comp/DrawControl'
import ShipLegend from './comp/ShipLegend'
import AreaHistory from './comp/AreaHistory'
import defData from './SeaChartDefaultData'
import drag from '@/utils/drag.js'
import {createMap, showTrack, locateShip, clearShipTrick} from './LLMap'

import * as keyShipService from '@/services/KeyShipService'
import * as flotillaService from '@/services/FlotillaService'
import * as shipService from '@/services/ShipService'
import * as authService from '@/services/AuthService'
import * as dataOpenService from '@/services/DataOpenService'
import DataTable from '@/components/common/DataTable.vue'
import Config from '@/config/index.js'

export default {
  components: {
    vship,
    varea,
    ttable,
    MapDraw,
    ShipLegend,
    AreaHistory,
    'data-table': DataTable,
  },
  computed: {
    width: function () {
      return document.body.clientWidth * 0.8
    },
    height: function () {
      return document.body.clientHeight * 0.6
    }
  },
  data: () => defData,
  mounted: function () {
    this.ulevel = localStorage.getItem('ulevel')
    if (window.screen.width < 1280) {
      this.wwdith = '98%'
    }
    if (localStorage.getItem('simplePWD')) {
      this.modifypwd = true
    }
    this.$root.eventHub.$on('shipMSG', (id) => {
    })
    this.$root.eventHub.$on('ad', (id) => {
      this.bgImg = []
      this.fileImg = []
    })
    this.$root.eventHub.$on('soll', (res) => {
      if (res == false) {
        this.width1 = '250px'
      } else {
        this.width1 = '40px'
      }
    })
    this.$root.eventHub.$on('show', (res) => {
      if (res == false) {
        this.show = 'none'
      } else {
        this.show = 'block'
        this.width1 = '0px'
      }
    })
    // idalog的监听
    this.$root.eventHub.$on('dialog', (res) => {
      if (res == 'false') {
        sessionStorage.removeItem('dialog')
      } else {
        sessionStorage.setItem('dialog', 'true')
      }
    })

    this.$root.eventHub.$on('fs', (res) => {
      this.wwdith = '100%'
      this.fullscreen = true
    })
    this.getMap()
    this.getFlotilla()
    drag(this.$refs.ship_detail_title, this.$refs.shipDetail)
  },
  created () {
    let token = localStorage.getItem('token')
    if (!token) {
      this.$router.replace('/login')
    }
  },
  methods: {
    handleData (key, content) {
      let str = ''
      if (key == 'EXPDATE_START' || key == 'EXPDATE_END' || key == 'AD_TIME' || key == 'INSPECT_DATE') {
        str = this.$m(content).format('YYYY-MM-DD')
      } else if (key == 'PRELIMINARY_REVIEW_SIGN') {
        str = content == 0 ? '初查' : '复查'
      } else {
        str = content
      }
      return str
    },
    // 危险品 弹层
    dangerousGoodsDeclaration () {
      this.makeQuery(this.boatinfo, 'mmsi').then(str => {
        dataOpenService.getLiquidData(str).then(res => {
          if (res.status == 200) {
            let data = res.data ? res.data.result : null
            if (!data) {
              this.$message({
                message: '暂无数据',
                type: 'warning'
              })
              return false
            }
            this.dangerousGoodsData1 = data
            this.dangerousGoodsDialog = true
          }
        })
        dataOpenService.getSolidData(str).then(res => {
          if (res.status == 200) {
            let data = res.data ? res.data.result : null
            if (!data) {
              this.$message({
                message: '暂无数据',
                type: 'warning'
              })
              return false
            }
            this.dangerousGoodsData2 = data
            // this.shipHistryInOutPortDialog = true
          }
        })
        dataOpenService.getPackData(str).then(res => {
          if (res.status == 200) {
            let data = res.data ? res.data.result : null
            if (!data) {
              this.$message({
                message: '暂无数据',
                type: 'warning'
              })
              return false
            }
            this.dangerousGoodsData3 = data
            // this.shipHistryInOutPortDialog = true
          }
        })
      })
    },
    // 船舶历史进出港 弹层
    shipHistryInOutPort () {
      this.makeQuery(this.boatinfo, 'id').then(str => {
        if (this.boatinfo.shipId) {
          if (this.boatinfo.shipId.substring(0, 2) == 'CN') {
            dataOpenService.getShipreportData(str).then(res => {
              if (res.status == 200) {
                let data = res.data ? res.data.result : null
                if (!data) {
                  this.$message({
                    message: '暂无数据',
                    type: 'warning'
                  })
                  return false
                }
                this.shipHistryInOutPortData = data
                this.shipHistryInOutPortDialog = true
              }
            })
          } else {
            dataOpenService.getShipExportInspect(str).then(res => {
              if (res.status == 200) {
                let data = res.data ? res.data.result : null
                if (!data) {
                  this.$message({
                    message: '暂无数据',
                    type: 'warning'
                  })
                  return false
                }
                this.shipHistryInOutPortData = data
                this.shipHistryInOutPortDialog = true
              }
            })
          }
        } else {
          this.$message({
            message: '暂无数据',
            type: 'warning'
          })
          return false
        }
      })
    },
    // 船舶安检情况 弹层
    shipPSC () {
      if (this.boatinfo.shipId) {
        if (this.boatinfo.shipId.substring(0,2) == 'CN') {
          this.makeQuery(this.boatinfo, 'id').then(str => {
            dataOpenService.getShipStateControl(str).then(res => {
              if (res.status == 200) {
                let data = res.data ? res.data.result : null
                if (!data) {
                  this.$message({
                    message: '暂无数据',
                    type: 'warning'
                  })
                  return false
                }
                this.shipPSCDialog = true
                this.shipPSCData = data
              }
            })
          })
        } else {
          this.makeQuery(this.boatinfo, 'callsign').then(str => {
            dataOpenService.getShipInspFormA(str).then(res => {
              if (res.status == 200) {
                let data = res.data ? res.data.result : null
                if (!data) {
                  this.$message({
                    message: '暂无数据',
                    type: 'warning'
                  })
                  return false
                }
                this.shipPSCDialog = true
                this.shipPSCData = data
              }
            })
          })
        }
      } else {
        this.$message({
          message: '暂无数据',
          type: 'warning'
        })
        return false
      }
    },
    // 安检情况详情
    showShipPSCInfo (data) {
      this.shipPSCInfo = data
      this.shipPSCInfoDialog = true
    },
    // 船舶最低安全配员证书 弹层
    shipSafeCertificate () {
      this.makeQuery(this.boatinfo, 'id').then(str => {
        dataOpenService.getShipManningDataODS(str).then(res => {
          if (res.status == 200) {
            let data = res.data ? res.data.result : null
            if (!data) {
              this.$message({
                message: '暂无数据',
                type: 'warning'
              })
              return false
            }
            if (data.length > 0) {
              let shipInfo = data.find(item => {
                return item.SHIP_NAME_CN == this.boatinfo.shipNameCn && item.SHIP_NAME_EN == this.boatinfo.shipNameEn
              })
              this.safeCertificateDialog = true
              this.shipSafeInfo = shipInfo
            }
          }
        })
      })
    },
    safeCertificateDataAction () {

    },
    safeCertificateCurrentChange () {

    },
    makeQuery (data, type) {
      return new Promise((resolve, reject) => {
        let today = this.$m(new Date())
        let targetTime = this.$m(localStorage.getItem('expires_date'))
        let diff = targetTime.diff(today, 'hour')
        let str = ''
        if (type == 'mmsi') {
          str += `ship_mmsi=${data.shipId ? data.shipId : ''}`
          str += `&ship_id=${data.shipId ? data.shipId : ''}`
        } else if(type == 'callsign') {
          str += `ship_callsign=${data.shipId ? data.shipId : ''}`
          str += `&ship_name_en=${data.shipNameEn ? data.shipNameEn : ''}`
        } else if(type == 'id') {
          str += `ship_id=${data.shipId ? data.shipId : ''}`
          str += `&ship_name_cn=${data.shipNameCn ? data.shipNameCn : ''}`
          str += `&ship_name_en=${data.shipNameEn ? data.shipNameEn : ''}`
        }
        str += `&appid=${Config.appId ? Config.appId : ''}`
        if (localStorage.getItem('access_token') && diff > 2) {
          str += `&access_token=${localStorage.getItem('access_token')}`
          resolve(str)
        } else {
          authService.getToken().then(resp => {
            if (resp.status == 200) {
              localStorage.setItem('access_token', resp.data.access_token)
              localStorage.setItem('expires_date', resp.data.expires_date)
              str += `&access_token=${resp.data.access_token}`
              resolve(str)
            } else {
              reject(resp)
            }
          })
        }
      })
    },
    // search 函数
    searchShip () {
      if (this.timeOt) {
        clearTimeout(this.timeOt);
      }
      this.timeOt = setTimeout(() => {
        let str = this.searchKeyword.toUpperCase();
        str = str.replace(/\s*/g,"")
        if (str.length < 2) {
          return;
        }
        var querystr = 'search=' + str
        // 发送请求, 然后拼出如下格式, -------------------------
        shipService.searchPS(querystr).then(async res => {
          if (res.length == 1) {
            // this.searchCheck(res[0])
            this.showShipDetail(res[0], true);
            this.showSearchResult = false;
          } else if(res.length > 1) {
            // this.searchFlag = true
            this.showSearchResult = true
            this.searchResult = res
            // this.searchList = res
          } else {
            this.showSearchResult = true;
            this.searchResult = []
          }
        })
      }, 500)
    },
    // 显示船舶
    showShipDetail (val, locate) {
      this.showSearchResult = false;
      shipService.getDetial(val.mmsi, val.enName).then((retinfod) => {
        this.tempshipdetial = this.convertOneShipDetial(retinfod)
        this.shipdetail = true

        if (this.tempshipdetial.ship) {
          this.boatinfo = this.tempshipdetial.ship
        } else {
          // this.shipEnName = enName
        }
        if (this.tempshipdetial.ais) {
          if (this.tempshipdetial.ais.trueheading == -1) {
            this.tempshipdetial.ais.trueheading = this.tempshipdetial.ais.course
          }
          this.boatAis = this.tempshipdetial.ais
          if (this.tempshipdetial.ais.utc) {
            this.boatinfo.operatetime = new Date(this.tempshipdetial.ais.utc * 1000).pattern('yyyy-MM-dd hh:mm:ss')
          }
        }

        this.locateShip()
      })
    },
    // 关闭搜索框下拉
    closeSearch () {
      this.showSearchResult = false
    },
    getMap () {
      createMap.call(this, this)
    },
    // 添加关注区域
    addImportarea () {
      if (!this.tianjia) {
        this.tianjia = true
        document.getElementById('mapshipmap').style.cursor = 'crosshair'
        this.$message('请在地图上选择你要添加到重点区域的中心点位置')
      } else {
        this.tianjia = false
        document.getElementById('mapshipmap').style.cursor = '-webkit-grab'
        document.getElementById('mapshipmap').style.cursor = '-moz-grab'
        this.$message('您已取消此次添加')
      }
    },
    // 创建船队、点击某个船队的命令入口
    handleCommandShipTeam (id) {
      if (id == 'createShipTeam') {
        this.createShipTeam()
      } else {
        this.flotillaClick(id)
      }
    },
    // 地图切换,界面上线屏蔽了
    // handleCommand1(id) {

    //     this.map.removeLayer(this.shipTile)
    //     this.map.removeLayer(this.osm)
    //     if (id == '1') {
    //         this.mapTxt='基本'
    //     } else  if(id=='2'){
    //         this.mapTxt='标准'
    //     }else{
    //         this.mapTxt='全部'
    //     }
    //     // var osmUrl = this.$config['outw'] + '/{z}/{x}/{y}?dc='+id;
    //     // var osmUrl=this.$config['innw']+'/{z}/{x}/{y}?dc='+id;
    //     var osmAttrib = 'Map data &copy; 国交信通 contributors';
    //      this.osm = new L.TileLayer(osmUrl, {
    //         minZoom: 1,
    //         maxZoom: 18,
    //         zIndex:0,
    //         attribution: osmAttrib
    //     });
    //     // var shipUrl = this.$config['outship'] + '/{z}/{x}/{y}';
    // var shipUrl=this.$config['inship']+'/{z}/{x}/{y}';
    // this.shipTile = new L.TileLayer(shipUrl, {
    //     minZoom: 1,
    //     maxZoom: 10,
    //     zIndex:1
    // });

    // //船位瓦片
    // this.map.addLayer(this.osm);
    // this.map.addLayer(this.shipTile);
    // },
    close () {
      if (this.fullscreen == true) {
        this.fullscreen = false
        if (window.screen.width < 1280) {
          this.wwdith = '98%'
        } else {
          this.wwdith = '86%'
        }
      }
      sessionStorage.removeItem('dialog')
    },
    // 点击具体船队的名称对话框关闭
    closeFlotillaDialog () {
      this.flotillaDialog = false
    },
    // 获取一个船队的数据
    getOneFlotillaData () {
      this.flotillaName = ''
      this.totalData = []
      for (let i = 0; i < this.flotillaList.length; i++) {
        if (this.flotillaList[i].id == this.flotillaId) {
          this.flotillaName = this.flotillaList[i].name
          if (this.flotillaList[i].ships) {
            for (let k = 0; k < this.flotillaList[i].ships.length; k++) {
              this.totalData.push(this.flotillaList[i].ships[k])
            }
          }
          break
        }
      }
      this.pageJs()
    },
    // 计算表格的分页数据和当前页数据
    pageJs () {
      this.totalRec = this.totalData.length
      this.currentPage = 1
      this.tableData = []
      if (this.totalData.length == 0) {
        this.totalPage = 0
      } else {
        let tempTotalPage = this.totalData.length / this.pagesize
        let xswz = String(tempTotalPage).indexOf('.') + 1// 获取小数点的位置
        if (xswz > 0) {
          this.totalPage = parseInt(tempTotalPage) + 1
        } else {
          this.totalPage = tempTotalPage
        }
        this.pageJsOnePageData()
      }
    },
    pageJsOnePageData () {
      this.tableData = []
      var startindex = (this.currentPage - 1) * this.pagesize
      var endindex = this.currentPage * this.pagesize - 1
      if (endindex > this.totalData.length - 1) {
        endindex = this.totalData.length - 1
      }
      for (let k = startindex; k <= endindex; k++) {
        this.tableData.push(this.totalData[k])
      }
    },
    // 点击某个船队对话框-每页多少条
    handleSizeChange (val) {
      this.pageJs()
    },
    // 点击某个船队对话框-改变页吗
    handleCurrentChange (val) {
      this.currentPage = val
      this.pageJsOnePageData()
    },
    // 点击具体船队的名称
    flotillaClick (id) {
      this.flotillaId = id
      this.getOneFlotillaData()
      this.flotillaDialog = true
    },
    // 点击某个船队对话框-编辑船队
    editdelete () {
      this.$prompt('请输入船队名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        inputErrorMessage: '船队名称不能为空',
        inputValue: this.flotillaName,
        customClass: 'customClass'
      }).then(async ({
                       value
                     }) => {
        var obj = {}
        var ships = []
        for (let i = 0; i < this.flotillaList.length; i++) {
          if (this.flotillaList[i].id == this.flotillaId) {
            obj.id = this.flotillaList[i].id
            obj.name = value
            obj.sysUserId = this.flotillaList[i].sysUserId
            obj.color = this.flotillaList[i].color
            obj.createTime = this.flotillaList[i].createTime
            obj.updateTime = this.flotillaList[i].updateTime
            if (this.flotillaList[i].ships) {
              for (let k = 0; k < this.flotillaList[i].ships.length; k++) {
                ships.push({id: this.flotillaList[i].ships[k].id})
              }
            }
            break
          }
        }
        obj.ships = ships
        let retobj = await flotillaService.updateFlotillas(obj)
        if (retobj != null && retobj != 'null') {
          this.$message({message: '操作成功', type: 'success'})
          this.getFlotilla()
        } else {
          this.$message.error('操作失败！')
        }
      }).catch(() => {
        this.$message('您已取消此次编辑')
      })
    },
    // 点击某个船队对话框-删除船队
    teamdelete () {
      this.$confirm('是否确认删除船队', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        let retobj = await flotillaService.deleteFlotillas(this.flotillaId)
        if (retobj != null && retobj != 'null') {
          this.flotillaId = ''
          this.$message({message: '操作成功', type: 'success'})
          this.closeFlotillaDialog()
          this.getFlotilla()
        } else {
          this.$message.error('操作失败！')
        }
      })
    },
    // 点击某个船队对话框-船舶记录的操作
    shipcaozuo (s) {
      var doing = s.split('-')
      var item = this.tableData[doing[1]]
      if (doing[0] == 'look') {
        let shipid = item.id
        var oneship = null
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id == shipid) {
            oneship = this.tableData[i]
          }
        }
        let mmsi = oneship.mmsi
        var enName = oneship.enName
        this.seeOneShipDetiall(mmsi, enName)
      } else if (doing[0] == 'del') {
        this.flotillaDelShip(item.id)
      }
    },
    getOneShipDetial (mmsi, shipNameEn) {
      let deatilinfo = shipService.getDetial(mmsi, shipNameEn)
      return deatilinfo
    },
// 查询船舶详情后对象的转换，和LLMap.js中的 convertDetial 一致，如改则同时改
    convertOneShipDetial (retinfod) {
      if (retinfod) {
        let retinfod1 = {}
        let ship = {}
        ship.id = retinfod.id
        ship.shipNameCn = retinfod.cnName
        ship.shipNameEn = retinfod.enName
        ship.mmsi = retinfod.mmsi
        ship.shipClass = retinfod.shipClass
        ship.shipTypeNameCn = retinfod.typeNameCn
        ship.shipImo = retinfod.imo
        ship.shipCallsign = retinfod.callsign
        ship.shipRouteCode = retinfod.routeCode
        ship.sailingareaName = retinfod.sailingAreaName
        ship.shipGrosston = retinfod.grossTonnage
        ship.shipNetton = retinfod.netTonnage
        ship.shipLength = retinfod.shipLength
        ship.shipBreadth = retinfod.shipWidth
        ship.shipDepth = retinfod.shipDepth
        ship.shipPassengerNum = retinfod.passengerCount
        ship.shpParkingNum = retinfod.parkingCount
        ship.shipWindLevel = retinfod.windLevel
        ship.rescueEquipmentNum = retinfod.rescueEqMax
        ship.minSafeManningNum = retinfod.safeManningMin
        ship.regportName = retinfod.regPortName
        ship.shipOwner = retinfod.owner
        ship.shipOperator = retinfod.operator
        ship.shipEnginePower = retinfod.enginePower
        ship.shipEngineNum = retinfod.engineCount
        ship.engineTypeNameCn = retinfod.engineTypeNameCn
        ship.shipNo = retinfod.shipNo
        ship.shipRegNo = retinfod.regNo
        ship.shipId = retinfod.shipCode

        retinfod1.ship = ship
        retinfod1.ais = retinfod.ais
        return retinfod1
      } else {
        let retinfod1 = {}
        retinfod1.ship = null
        retinfod1.ais = null
        return retinfod1
      }
    },
    seeOneShipDetiall (mmsi, enName) {
      this.getOneShipDetial(mmsi, enName).then((retinfod) => {
        this.tempshipdetial = this.convertOneShipDetial(retinfod)
        this.shipdetail = true

        if (this.tempshipdetial.ship) {
          this.boatinfo = this.tempshipdetial.ship
        } else {
          this.shipEnName = enName
        }
        if (this.tempshipdetial.ais) {
          if (this.tempshipdetial.ais.trueheading == -1) {
            this.tempshipdetial.ais.trueheading = this.tempshipdetial.ais.course
          }
          this.boatAis = this.tempshipdetial.ais
          if (this.tempshipdetial.ais.utc) {
            this.boatinfo.operatetime = new Date(this.tempshipdetial.ais.utc * 1000).pattern('yyyy-MM-dd hh:mm:ss')
          }
        }
      })
    },
    // 点击某个船队对话框-船舶记录的操作-删除
    async flotillaDelShip (shipid) {
      var obj = {}
      var ships = []
      for (let i = 0; i < this.flotillaList.length; i++) {
        if (this.flotillaList[i].id == this.flotillaId) {
          obj.id = this.flotillaList[i].id
          obj.name = this.flotillaList[i].name
          obj.sysUserId = this.flotillaList[i].sysUserId
          obj.color = this.flotillaList[i].color
          obj.createTime = this.flotillaList[i].createTime
          obj.updateTime = this.flotillaList[i].updateTime
          for (let k = 0; k < this.flotillaList[i].ships.length; k++) {
            if (this.flotillaList[i].ships[k].id != shipid) {
              ships.push({id: this.flotillaList[i].ships[k].id})
            }
          }
          break
        }
      }
      obj.ships = ships
      let retobj = await flotillaService.updateFlotillas(obj)
      if (retobj != null && retobj != 'null') {
        this.$message({message: '删除船舶成功', type: 'success'})
        this.getFlotilla()
      } else {
        this.$message.error('删除船舶失败！')
      }
    },
    // 创建船队
    createShipTeam () {
      this.cteateteamshow = true
    },
    // 创建船队-确定
    async createteamAddsure () {
      if (!this.form.name) {
        this.$alert('请输入船队名称')
        return false
      }
      let name = this.form.name
      let usierid = this.$profile.id
      this.shipFleetCreatLoading = true
      let retobj = await flotillaService.createFlotilla(name, usierid)
      if (retobj != null && retobj != 'null') {
        this.$message({message: '操作成功', type: 'success'})
        this.shipFleetCreatLoading = false
        this.createteamaddcancel()
        this.getFlotilla()
      } else {
        this.shipFleetCreatLoading = false
        this.$message.error('操作失败！')
      }
    },
    // 创建船队-取消
    createteamaddcancel () {
      this.cteateteamshow = false
    },
    // 获取船队
    async getFlotilla () {
      let usierid = this.$profile.id
      let retobj = await flotillaService.search(usierid)
      this.flotillaList = retobj
      if (this.flotillaId != '') {
        this.getOneFlotillaData()
      }
    },
    // 海图漫游，index=0，
    changeMap (index) {
      this.mapindex = index
      if (index == 0) {
        this.$nextTick(() => {
          this.getMap()
          this.map.setView(new L.LatLng(37.8, 120.7), 8)
        })
      } else {
        this.shipdetail = false
      }
    },
    // reDraw () {
    //   redrawMap.call(this, this)
    // },
    // updateData () {
    //   updateMap.call(this, this)
    // },
    // time () {
    //   if ((new Date()).getTime() - this.prevTime >= 2000) {
    //     this.updateData()
    //     this.prevTime = (new Date()).getTime()
    //   }
    //   if ((new Date()).getTime() - this.prevDraw >= 200) {
    //     this.reDraw()
    //     this.prevDraw = (new Date()).getTime()
    //   }
    //   setTimeout(() => {
    //     this.time()
    //   }, 1000)
    // },
    // 重点区域的切换调用
    qiehuan (data) {
      this.mapindex = 0
      this.$nextTick(res => {
        this.getMap()
        if (data[0] != 0 && data[1] != 0) {
          this.map.flyTo(data, 11)
        }
      })
    },
    // 重点船舶的切换调用
    qiehuan1 (data) {
      this.mapindex = 0
      this.$nextTick(res => {
        this.getMap()
        if (data[0] != 0 && data[1] != 0) {
          this.map.flyTo(data, 11)
        }
      })
    },
    locateShip () {
      // console.log('ship.........', this.boatinfo, this.boatAis)
      let position = L.latLng(this.boatAis.latitude, this.boatAis.longitude)
      if (this.map.getZoom() < 11) {
        this.map.setView(position, 11)
      } else {
        this.map.setView(position)
      }

      locateShip(this.boatinfo.mmsi, false)
    },
    // 船舶详情关闭
    shipClose () {
      this.shipdetail = false
      this.boatinfo = {}
      this.boatAis = {}
      // if (this.polyline) {
      //   this.polyline.remove()
      // }
    },
    // 关闭船舶详情-添加船队 的对话框
    closeAddShipToFlotillaDialog () {
      this.addToship = false
    },
    // 船舶详情-添加到船队-对话框的确定
    async addToSure () {
      var flotillaId = this.flotillaId
      var shipobj = {id: this.boatinfo.id}
      var obj = {}
      var ships = []
      var isexit = false
      for (let i = 0; i < this.flotillaList.length; i++) {
        if (this.flotillaList[i].id == flotillaId) {
          obj.id = this.flotillaList[i].id
          obj.name = this.flotillaList[i].name
          obj.sysUserId = this.flotillaList[i].sysUserId
          obj.color = this.flotillaList[i].color
          obj.createTime = this.flotillaList[i].createTime
          obj.updateTime = this.flotillaList[i].updateTime
          if (this.flotillaList[i].ships) {
            for (let k = 0; k < this.flotillaList[i].ships.length; k++) {
              ships.push({id: this.flotillaList[i].ships[k].id})
            }
          }
          isexit = true
          break
        }
      }
      if (isexit) {
        obj.ships = ships
        obj.ships.push(shipobj)
        let retobj = await flotillaService.updateFlotillas(obj)
        if (retobj != null && retobj != 'null') {
          this.$message({message: '操作成功', type: 'success'})
          this.getFlotilla()
          this.closeAddShipToFlotillaDialog()
        } else {
          this.$message.error('操作失败！')
        }
      } else {
        this.$message.error('请选择船队！')
      }
    },
    // 船舶详情-重点关注(也就是添加到关注船舶、也就是重点船舶）
    async addToiship () {
      var id = this.boatinfo.id
      if (id) {
        let terminalType = this.boatAis.postype
        let mmsi = this.boatinfo.mmsi
        let usierid = this.$profile.id
        let retobj = await keyShipService.saveKeyShip(id, mmsi, terminalType, usierid)
        if (retobj != null && retobj != 'null') {
          this.gengxin1++
          this.$message({message: '操作成功', type: 'success'})
        } else {
          this.$message.error('操作失败！')
        }
      } else {
        this.$message.error('此船不存在！')
      }
    },
    // 显示 轨迹查询 对话框
    showTrackDialog () {
      this.trackDialog = true
    },
    // 关闭 船舶详情点击 轨迹后的轨迹查询 对话框
    closeTrackDialog () {
      this.shipTrickLoading = false
      this.trackDialog = false
    },
    formatDateFULL (newDate) {
      return this.$m(newDate).format('YYYY-MM-DD HH:mm:ss')
      // var year = newDate.getFullYear()
      // var month = (newDate.getMonth() + 1) < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1
      // var day = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate()
      // var hours = newDate.getHours() < 10 ? '0' + newDate.getHours() : newDate.getHours()
      // var minuts = newDate.getMinutes() < 10 ? '0' + newDate.getMinutes() : newDate.getMinutes()
      // var seconds = newDate.getSeconds() < 10 ? '0' + newDate.getSeconds() : newDate.getSeconds()
      // var ret = year + '-' + month + '-' + day + ' ' + hours + ':' + minuts + ':' + seconds
      // return ret
    },
    //
    getSearchTrack (terminalCode, searchStartTime, searchEndTime) {
      let tracklist = shipService.findLocationHis(terminalCode, searchStartTime, searchEndTime)
      return tracklist
    },
    // 轨迹查询
    searchTrack () {
      this.shipTrickLoading = false
      this.tracklist = []
      // let shipid=this.boatinfo.id;
      // let shipNameCn=this.boatinfo.shipNameCn;
      // let shipNameEn=this.boatinfo.shipNameEn;
      let mmsi = this.boatinfo.mmsi
      // mmsi='900168868';
      let startDate = this.trackStart
      let endDate = this.trackEnd

      let sta_str = startDate.replace(/-/g, '/')
      let sta_date = new Date(sta_str)
      let end_str = endDate.replace(/-/g, '/')
      let end_date = new Date(end_str)
      var numsjc = (end_date - sta_date) / 1000// 求出两个时间的时间差（秒）
      let bjsen = 7 * 24 * 60 * 60
      if (numsjc > bjsen) {
        this.$message({message: '查询时间间隔最大为7天！', type: 'success'})
      } else {
        this.shipTrickLoading = true
        // let utcstart = sta_date.getTime() - 8 * 60 * 60 * 1000;
        // let utcend = end_date.getTime() - 8 * 60 * 60 * 1000;
        let utcstart = sta_date.getTime()
        let utcend = end_date.getTime()
        let utcstart_str = this.formatDateFULL(new Date(utcstart))
        let utcend_str = this.formatDateFULL(new Date(utcend))
        this.getSearchTrack(mmsi, utcstart_str, utcend_str).then((retinfod) => {
          this.shipTrickLoading = false
          if (retinfod != null && retinfod.length > 0) {
            for (let n = 0; n < retinfod.length; n++) {
              let onetrick = retinfod[n]
              let onetrickconvert = {}
              onetrickconvert.lng = onetrick.longitude
              onetrickconvert.lat = onetrick.latitude
              onetrickconvert.gpstime = this.$m(onetrick.aisTime).format('YYYY-MM-DD HH:mm')
              // onetrickconvert.gpstime = onetrickconvert.gpstime.substring(0, 10) + ' ' + onetrickconvert.gpstime.substring(11, 19)
              this.tracklist.push(onetrickconvert)
            }
            this.closeTrackDialog()
            showTrack.call(this, this)
          } else {
            this.$message({message: '无轨迹数据', type: 'success'})
          }
        })
      }
    },
    clearShipTrickClick () {
      clearShipTrick.call(this, this)
    },
    // showShipTrickGpsLabel () {
    //   showGpsLabel.call(this, this)
    // },
    // hideShipTrickGpsLabel () {
    //   hideGpsLabel.call(this, this)
    // },
    // 船舶搜输入框改变，原来老系统也没实现，所以暂时不实现
    inputSearch () {
    },
    getOneShipDetialForQuery (query) {
      let deatilinfo = shipService.search(query)
      return deatilinfo
    },
    // 船舶搜索
    async searchShipDeatil () {
      this.searchNameShow = true
      return false

      if (this.searchinfo == '') {
        this.$message({message: '请输入搜索内容!', type: 'success'})
        return
      }
      var querystr = ''
      if (this.select == 'mmsi') {
        querystr = 'mmsi==' + this.searchinfo
      } else if (this.select == 'ship_name_en') {
        querystr = 'enName==' + this.searchinfo
      } else if (this.select == 'ship_imo') {
        querystr = 'imo==' + this.searchinfo
      } else if (this.select == 'ship_name_cn') {
        querystr = 'cnName==' + this.searchinfo
      }
      this.boatinfo = {}
      this.boatAis = {}
      this.getOneShipDetialForQuery(querystr).then((retinfod) => {
        if (retinfod != null && retinfod.length > 0) {
          let oneobj = retinfod[0]
          this.tempshipdetial = this.convertOneShipDetial(oneobj)
          this.shipSearchIsRec = true
        } else {
          this.tempshipdetial = this.convertOneShipDetial(null)
          this.shipSearchIsRec = false
        }
        if (this.shipSearchIsRec) {
          this.shipdetail = true
        }
      // }).then(() => {
        if (this.shipSearchIsRec) {
          if (this.tempshipdetial.ship) {
            this.boatinfo = this.tempshipdetial.ship
          }
          if (this.tempshipdetial.ais) {
            this.boatAis = this.tempshipdetial.ais
            if (this.boatAis && this.boatAis.trueheading && this.boatAis.trueheading == -1) {
              this.boatAis.trueheading = this.boatAis.course
            }
            if (this.boatAis && this.boatAis.utc) {
              this.boatinfo.operatetime = new Date(this.boatAis.utc * 1000).pattern('yyyy-MM-dd hh:mm:ss')
            }
          }
        } else {
          this.$message({message: '无此船舶', type: 'success'})
        }
      })
    },
    // 船舶查询后船舶列表中点击某个船舶的事件，原来老系统中船舶搜索后就直接是精确搜索，不是模糊搜，所以也不显示列表，所以不实现
    chooseSearch (val, id) {
    },
    // 船舶详情上的创建任务
    shipTask (info) {
      this.shipdetail = false
      let shipid = this.boatinfo.id
      let shipNameCn = this.boatinfo.shipNameCn
      let shipNameEn = this.boatinfo.shipNameEn
      let mmsi = this.boatinfo.mmsi
      let par = {}
      par.nameEn = shipNameEn
      par.nameCn = shipNameCn
      par.mmsi = mmsi
      // let name = (this.boatinfo.shipNameCn ? this.boatinfo.shipNameCn + ' ' : '') + (this.boatinfo.shipNameEn ? this.boatinfo.shipNameEn : '')
      // this.$router.push({path: '/everyday-task/create', query: par})
      this.$router.push({name: 'CreateEverydayTask', query: par})
      info = []
    },
    onCancel () {
      // localStorage.removeItem('ms_username')
      // localStorage.removeItem('auth')
      // localStorage.removeItem('permission')
      // localStorage.removeItem('myLog')
      // localStorage.removeItem('mySummary')
      // localStorage.removeItem('org_id')
      // localStorage.removeItem('ulevel')
      // localStorage.removeItem('admin')
      this.$router.replace('../login')
    },
    makeTimeString (timeStr) {
      if (!timeStr) {
        return '暂无'
      }
      let diff = new Date().getTime() - this.$m(timeStr)._d.getTime()
      let mins = parseInt(diff / 1000 / 60, 10)
      if (mins <= 1) {
        return '刚刚'
      } else if (mins < 60) {
        return mins + '分钟前'
      } else if (mins < 1440) {
        return parseInt(mins / 60, 10) + '小时前'
      } else {
        return parseInt(mins / 1440, 10) + '天前'
      }
    },
    // showMapLeng () {
    //   this.mapLegendDialog = true
    // }
  }
}
